package top.abrsm.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import top.abrsm.config.LogPointer;
import top.abrsm.entity.*;
import top.abrsm.service.*;
import top.abrsm.util.CommonUtil;
import top.abrsm.util.SnowflakeIdWorker;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 * 贴吧订单表：置顶充值、积分充值 前端控制器
 * </p>
 * @author WuZH
 * @since 2023-11-18
 */
@Controller
@RequestMapping ("/order")
@Slf4j
public class OrderController {

    @Resource
    private IProductService iProductService;
    @Resource
    private IFileService iFileService;
    @Resource
    private IAddressService iAddressService;
    @Resource
    private IOrderService iOrderService;
    @Resource
    private ICarService iCarService;

    /**
     * 创建一个订单
     * @param productId
     * @param session
     * @param model
     * @return
     */
    @RequestMapping ("orderInfo")
    public String orderInfo (@Param ("productId") String productId, @RequestParam(value = "carId", required = false) String carId, HttpSession session, Model model) {
        StudentEntity studentEntity = (StudentEntity) session.getAttribute ( "studentEntity" );
        ProductEntity productEntity = new ProductEntity ();
        productEntity.setId ( productId );
        productEntity = iProductService.querySingle ( productEntity );
        FileEntity fileEntity = new FileEntity ();
        fileEntity.setFileJoinId ( productEntity.getId () );
        fileEntity.setFileJoinType ( 2 );
        List<FileEntity> fileEntities = iFileService.queryList ( fileEntity );
        productEntity.setFileEntities ( fileEntities );
        model.addAttribute ( "productEntity", productEntity );
        AddressEntity addressEntity = new AddressEntity ();
        addressEntity.setStuId ( studentEntity.getId () );
        List<AddressEntity> addressEntities = iAddressService.queryList ( addressEntity );
        model.addAttribute ( "addressEntities", addressEntities );
        model.addAttribute ( "carId", carId );
        return "submit";
    }


    /**
     * 提交订单，生成订单
     * @param productId
     * @return
     */
    @RequestMapping ("createOrder")
    public String createOrder (@Param ("productId") String productId, @RequestParam(value = "carId", required = false) String carId, HttpSession session, Model model) {
        StudentEntity studentEntity = (StudentEntity) session.getAttribute ( "studentEntity" );
        // 检查是否有默认地址
        AddressEntity defaultAddress = new AddressEntity ();
        defaultAddress.setStuId ( studentEntity.getId () );
        defaultAddress.setIsDefault ( 1 );
        defaultAddress = iAddressService.querySingle ( defaultAddress );
        if ( defaultAddress == null ) {
            model.addAttribute ( "msg", "请选择一个默认邮寄地址" );
            return "redirect:/order/orderInfo?productId=" + productId;
        }
        //1. 获取用户是否登录
        ProductEntity productEntity = new ProductEntity ();
        productEntity.setId ( productId );
        productEntity = iProductService.querySingle ( productEntity );
        //2. 获取商品信息并生成订单号
        StringBuffer stringBuffer = new StringBuffer ( CommonUtil.getFormatDateTime ( "yyyyMMddHHmmss" ) );
        stringBuffer.append ( CommonUtil.getRandom ( 16 ) );
        OrderEntity orderEntity = new OrderEntity ();
        orderEntity.setProductId ( productId );
        orderEntity.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
        orderEntity.setStuId ( studentEntity.getId () );
        orderEntity.setTradeStatus ( 0 );
        orderEntity.setActualPrice ( productEntity.getActualPrice () );
        orderEntity.setPayType ( 0 );
        orderEntity.setType ( 3 ); // 购物订单
        orderEntity.setOutTradeNo ( stringBuffer.toString () );
        orderEntity = iOrderService.saveSingle ( orderEntity );
        log.info ( "新订单创建成功->[商户订单号：{}]", orderEntity.getOutTradeNo () );
        // 删除购物车
        if ( StringUtils.isNotBlank ( carId ) ) {
            CarEntity carEntity = new CarEntity ();
            carEntity.setId ( carId );
            carEntity = iCarService.deleteSingle ( carEntity );
        }
        model.addAttribute ( "actualPrice", productEntity.getActualPrice () );
        model.addAttribute ( "outTradeNo", stringBuffer.toString () );
        model.addAttribute ( "productId", productId );
        model.addAttribute ( "productEntity", productEntity );
        return "pay";
    }


    /**
     * 查询订单列表
     * @param tradeStatus：订单状态
     * @param index：前端Tab页的下标
     * @param session
     * @param model
     * @return
     */
    @RequestMapping ("queryList")
    public String queryList (@RequestParam (value = "tradeStatus", required = false) Integer tradeStatus, @RequestParam (defaultValue = "0", value = "index") Integer index, HttpSession session, Model model) {
        StudentEntity studentEntity = (StudentEntity) session.getAttribute ( "studentEntity" );
        OrderEntity orderEntity = new OrderEntity ();
        orderEntity.setTradeStatus ( tradeStatus );
        orderEntity.setStuId ( studentEntity.getId () );
        List<OrderEntity> orderEntities = iOrderService.queryList ( orderEntity );
        model.addAttribute ( "orderEntities", orderEntities );
        model.addAttribute ( "index", index );
        return "orderList";
    }


    /**
     * 取消订单
     * @param id
     * @return
     */
    @RequestMapping ("deleteSingle")
    public String deleteSingle (@Param ("id") String id) {
        OrderEntity orderEntity = new OrderEntity ();
        orderEntity.setId ( id );
        orderEntity = iOrderService.deleteSingle ( orderEntity );
        return "redirect:/order/queryList";
    }

    /**
     * 确认收货，修改订单状态
     * @return
     */
    @RequestMapping ("queryReceipt")
    @LogPointer ("确认收货")
    public String queryReceipt (@Param ("id") String id) {
        OrderEntity orderEntity = new OrderEntity ();
        orderEntity.setId ( id );
        orderEntity.setTradeStatus ( 3 ); // 已收货
        orderEntity = iOrderService.updateSingle ( orderEntity );
        return "redirect:/order/queryList";
    }

}
